<template>
  <div class="menu-content indicator-list">
    <!-- <w-scrollbar wrap-class="scrollbar-wrapper"> -->
    <div class="left">
      <p class="right-title" style="margin-bottom: 20px;">指标清单</p>
      <div style="margin-bottom: 30px;text-align: right;width:100%;">
        <w-select style="width:30%" v-model="zbflName" placeholder="请选择" @change="zbflChange">
          <w-option v-for="item in zbflOptions" :key="item.zbflId" :label="item.zbflName" :value="item.zbflName">
          </w-option>
        </w-select>
        <w-input style="width:45%" placeholder="请输入指标名称" v-model="mzCost"></w-input>
        <w-button style="width:20%" type="primary" @click="query">查询</w-button>
      </div>
      <!-- <div :style="{'height': divHeight+'px','width':'400px','overflow':'scroll'}"> -->
      <el-scrollbar wrap-style="height:700px;margin-bottom:100px;" >
        <w-tree ref='tree' :accordion="true" highlight-current :current-node-key="zbId" node-key="zbId" :data="treeData" :props="defaultProps"
          @node-click="handleNodeClick"></w-tree>
      </el-scrollbar>
      <!-- </div> -->
    </div>
    <div id="right" class="right">
      <p style="height: 50px;"></p>
      <div style="position: relative;">
        <w-table border :max-height="tableHeight" :data="tableData" @cell-click="paramedit" @row-click="rowClick" @selection-change="handleSelectionChange"
          :row-style="rowStyle" :row-class-name="rowClassName" ref="multiTable">
          <w-table-column prop="compareOperator" label="规则">
            <template slot-scope="{row,$index}">
              <div class="input-box" v-if="showCompareOperator[$index]">
                <w-select v-model="row.compareOperator" placeholder="请选择" @change="handleCompare(row)">
                  <w-option v-for="item in ruleOptions" :key="item.id" :label="item.value" :value="item.value">
                  </w-option>
                </w-select>
              </div>
              <span v-if="!showCompareOperator[$index]">{{row.compareOperator}}</span>
            </template>
          </w-table-column>
          <w-table-column prop="lowestValue" label="低值">
            <template slot-scope="{row,$index}">
              <div class="input-box" v-if="row.compareOperator&&showLowestValue[$index]">
                <w-input size="small" v-model="row.lowestValue" @change="changeName(row)"></w-input>
              </div>
              <span v-if="!showLowestValue[$index]">{{row.lowestValue}}</span>
            </template>
          </w-table-column>
          <w-table-column prop="highestValue" label="高值">
            <template slot-scope="{row,$index}">
              <div class="input-box" v-if="row.compareOperator&&showHighestValue[$index]">
                <w-input size="small" v-model="row.highestValue" @change="changeName(row)"></w-input>
              </div>
              <span v-if="!showHighestValue[$index]">{{row.highestValue}}</span>
            </template>
          </w-table-column>
          <w-table-column prop="standardSource" label="标准">
            <template slot-scope="{row,$index}">
              <div class="input-box" v-if="showStandardSource[$index]">
                <w-select v-model="row.standardSourceName" placeholder="请选择" @change="standardChange(row)">
                  <w-option v-for="item in standardOptions" :key="item.value" :label="item.label" :value="item.value">
                  </w-option>
                </w-select>
              </div>
              <span v-if="!showStandardSource[$index]">{{row.standardSourceName}}</span>
            </template>
          </w-table-column>
          <w-table-column prop="status" label="调整" width="100">
            <template slot-scope="{row,$index}">
              <div class="input-box">
                <w-switch @change="switchChange(row)" v-model="row.status" active-color="#13ce66" inactive-color="#ff4949">
                </w-switch>
              </div>
            </template>
          </w-table-column>
          <w-table-column prop="remindMethod" label="提醒模式">
            <template slot-scope="{row,$index}">
              <div class="input-box" v-if="showRemindMethod[$index]">
                <w-select v-model="row.remindMethodName" placeholder="请选择" @change="remindChange(row)">
                  <w-option v-for="item in remindOptions" :key="item.value" :label="item.label" :value="item.value">
                  </w-option>
                </w-select>
              </div>
              <span v-if="!showRemindMethod[$index]">{{row.remindMethodName}}</span>
            </template>
          </w-table-column>
          <w-table-column prop="logicOperator" label="关系">
            <template slot-scope="{row,$index}">
              <div class="input-box" v-if="showLogicOperator[$index]">
                <w-select v-model="row.logicOperator" placeholder="请选择" @change="relationChange(row)">
                  <w-option key="1" label="并且" value="and">
                  </w-option>
                  <w-option key="0" label="或者" value="or">
                  </w-option>
                </w-select>
              </div>
              <span v-if="!showLogicOperator[$index]">{{row.logicOperator}}</span>
            </template>
          </w-table-column>
          <w-table-column prop="operator" label="操作">
            <template slot-scope="{row,$index}">
              <a title="删除" v-if="!row.add" class="reduce" @click="reduce(row)"><i class="w-icon-delete"></i></a>
              <a title="添加" v-if="row.add" class="add" @click="add(row)"><i class="w-icon-plus"></i></a>
            </template>
          </w-table-column>
        </w-table>
        <canvas id="canvas" width="50" height="120"></canvas>
      </div>
      <hr style="margin: 20px 0;" />
      <div class="sql-info">{{sqlText}}</div>
    </div>
    <!-- </w-scrollbar> -->

    <!--自定义右键菜单html代码-->
    <div id="menu">
      　<div class="menu">并且</div>
      　<div class="menu">或者</div>
      　<div class="menu">取消</div>
    </div>

  </div>
</template>
<script>
  import {
    getTopAndBottom
  } from '@/utils/index.js'
  export default {
    data() {
      return {
        zbId: '',
        zbName: '',
        mzCost: '', //门诊费用
        selectionRow: [],
        sqlText: '',
        showCompareOperator: [],
        showHighestValue: [],
        showLowestValue: [],
        showStandardSource: [],
        showRemindMethod: [],
        showLogicOperator: [],
        ruleOptions: [], //规则数组
        standardOptions: [], //标准数组
        remindOptions: [], //提醒模式数组
        isHigh: true,
        isLow: true,
        defaultProps: {
          children: 'children',
          label: 'zbName'
        },
        tableData: [],
        zbflName: '',
        zbflId: '',
        treeData: [],
        zbflOptions: [],
        divHeight: document.documentElement.clientHeight - 290,
        tableHeight: document.documentElement.clientHeight - 300,
      };
    },
    mounted() {
      // addEventListener("keydown", this.keyDown, false);
      // addEventListener("keyup", this.keyUp, false);
    },
    computed: { //实时得到最上行和最下行
      bottomSelectionRow() {
        if (this.selectionRow.length == 0) return null;
        return this.selectionRow.reduce((start, end) => {
          return start.rowIndex > end.rowIndex ? start : end;
        });
      },
      topSelectionRow() {
        if (this.selectionRow.length == 0) return null;
        return this.selectionRow.reduce((start, end) => {
          return start.rowIndex < end.rowIndex ? start : end;
        });
      }
    },
    created() {
      this.getTreeData()
      this.getZbflData()
      this.getRuleData("JSGZ")
      this.getRuleData("HYBZ")
      this.getRuleData("TXMS")
    },
    methods: {
      //switch点击切换
      switchChange(row) {
        if (row.status == 1) {
          row.status = true
        } else {
          row.status = false
        }
        if (!row.add) {
          this.editRuleData(row)
        }
      },
      //查询
      query() {
        this.getTreeData()
      },
      zbflChange(val) {
        this.zbflOptions.map((item, index) => {
          if (item.zbflName == val) {
            this.zbflId = item.zbflId
          }
        })
        this.getTreeData()
      },
      //获取涉及指标数据
      getZbflData() {
        this.$Http
          .post("etlProcedureIndicatorMap/findGroupByZbfl", {
            id: ''
          })
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              content.unshift({zbflId: "",zbflName: "全部"})
              this.zbflOptions = content
              this.zbflName = content[0].zbflName
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      changeName(row) {
        if (!row.add) {
          this.editRuleData(row)
        }
      },
      //修改提醒模式
      remindChange(row) {
        var remindMethod = ''
        this.remindOptions.map((i, k) => {
          if (i.value == row.remindMethodName) {
            remindMethod = i.id
          }
        })
        row.remindMethod = remindMethod
        if (!row.add) {
          this.editRuleData(row)
        }
      },
      relationChange(row){
        if (!row.add) {
          this.editRuleData(row)
        }
      },
      //修改标准
      standardChange(row) {
        var standardSource = ''
        this.standardOptions.map((i, k) => {
          if (i.value == row.standardSourceName) {
            standardSource = i.id
          }
        })
        row.standardSource = standardSource
        if (!row.add) {
          this.editRuleData(row)
        }
      },
      //修改规则
      handleCompare(row) {
        if (row.compareOperator == '大于') {
          row.isHigh = false
          row.isLow = true
          if (!row.lowestValue) {
            return false
          }
        } else if (row.compareOperator == '小于') {
          row.isLow = false
          row.isHigh = true
          if (!row.highestValue) {
            return false
          }
        } else if (row.compareOperator == '等于') {
          row.isLow = true
          row.isHigh = false
          if (!row.lowestValue) {
            return false
          }
        } else {
          row.isHigh = true
          row.isLow = true
          if (!row.lowestValue || !row.highestValue) {
            return false
          }
        }
        if (!row.add) {
          this.editRuleData(row)
        }
      },
      //获取涉及指标数据
      getTreeData() {
        this.$Http
          .post("etlProcedureIndicatorMap/findZbmxTree", {
            zbflId: this.zbflId,
            zbName: this.mzCost
          })
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              this.treeData = content
              this.getRulesData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //查找指标阈值规则管理表格数据
      getRulesData() {
        this.$Http
          .post("etlIndiThresholdRules/findtableListInfo", {
            zbId: this.zbId
          })
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              this.tableData = content
              this.sqlText = ''
              if (this.tableData.length > 0) {
                this.tableData.map((item, index) => {
                  if (item.status == 1) {
                    item.status = true
                  } else {
                    item.status = false
                  }
                  if (item.highestValue||item.highestValue=='0') {
                    item.isHigh = true
                  } else {
                    item.isHigh = false
                  }
                  if (item.lowestValue||item.lowestValue=='0') {
                    item.isLow = true
                  } else {
                    item.isLow = false
                  }
                })
                this.sqlText = content[0].sqlContext
              }
              if(this.zbId){
                this.tableData.push({
                  id: '',
                  add: true,
                  isHigh: true,
                  isLow: true,
                  status: true
                })
              }
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //编辑表格数据
      editRuleData(info) {
        let param = {
          id: info.id ? info.id : '',
          compareOperator: info.compareOperator ? info.compareOperator : '',
          highestValue: info.isHigh ? info.highestValue : '',
          lowestValue: info.isLow ? info.lowestValue : '',
          standardSource: info.standardSource ? info.standardSource : '',
          remindMethod: info.remindMethod ? info.remindMethod : '',
          logicOperator: info.logicOperator ? info.logicOperator : '',
          status: info.status ? 1 : 0,
          zbId: this.zbId,
          zbName: this.zbName
        }
        this.$Http
          .post("etlIndiThresholdRules/update", param)
          .then(response => {
            if (response.data.response.code == "1") {
              this.$message.success('编辑成功~')
              this.setShowEditInit()
              this.getRulesData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //点击添加步骤
      add(row) {
        if (!this.zbId) {
          this.$message.error('请先选择左侧指标哦~')
          return false
        }
        if (!row.compareOperator) {
          this.$message.error('选择规则')
        } else if (row.isHigh && !row.highestValue) {
          this.$message.error('请输入高值')
        } else if (row.isLow && !row.lowestValue) {
          this.$message.error('请输入低值')
        } else if (!row.standardSourceName) {
          this.$message.error('请选择标准')
        } else if (!row.remindMethodName) {
          this.$message.error('请选择提醒模式')
        } else if (!row.logicOperator) {
          this.$message.error('请选择关系')
        } else {
          let param = {
            id: '',
            compareOperator: row.compareOperator,
            highestValue: row.highestValue ? row.highestValue : '',
            lowestValue: row.lowestValue ? row.lowestValue : '',
            standardSource: row.standardSource,
            remindMethod: row.remindMethod,
            logicOperator: row.logicOperator,
            status: row.status ? 1 : 0,
            zbId: this.zbId,
            zbName: this.zbName
          }
          this.$Http
            .post("etlIndiThresholdRules/save", param)
            .then(response => {
              if (response.data.response.code == "1") {
                this.$message.success('新增成功~')
                this.setShowEditInit()
                this.getRulesData()
              } else {
                if (response.data.response.msg) {
                  this.$message.error(response.data.response.msg)
                }
              }
            })
            .catch(error => {
              console.log(error);
            });
        }
      },
      //点击删除步骤
      reduce(row) {
        this.$confirm('确认删除此条环节吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$Http
            .get("etlIndiThresholdRules/delete/" + row.id)
            .then(response => {
              if (response.data.response.code == "1") {
                this.$message.success('删除成功~')
                this.setShowEditInit()
                this.getRulesData()
              } else {
                if (response.data.response.msg) {
                  this.$message.error(response.data.response.msg)
                }
              }
            })
            .catch(error => {
              console.log(error);
            });
        }).catch(() => {

        });
      },
      //获取条件数据
      getRuleData(code) {
        let param = {
          typeCode: code
        }
        this.$Http
          .post("tableDicInfo/findTableDicInfo", param)
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              if (code == 'JSGZ') {
                this.ruleOptions = content
              } else if (code == 'HYBZ') {
                this.standardOptions = content
              } else if (code == 'TXMS') {
                this.remindOptions = content
              }
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      handleNodeClick(treeData) {
        if (!treeData.children) {
          this.zbId = treeData.zbId
          this.zbName = treeData.zbName
          this.getRulesData()
        }
      },
      // 初始化单元格显示状态
      setShowEditInit() {
        this.showCompareOperator.map((item, index) => {
          this.showCompareOperator[index] = false
        })
        this.showHighestValue.map((item, index) => {
          this.showHighestValue[index] = false
        })
        this.showLowestValue.map((item, index) => {
          this.showLowestValue[index] = false
        })
        this.showStandardSource.map((item, index) => {
          this.showStandardSource[index] = false
        })
        this.showRemindMethod.map((item, index) => {
          this.showRemindMethod[index] = false
        })
        this.showLogicOperator.map((item, index) => {
          this.showLogicOperator[index] = false
        })
      },
      //单击单元格事件
      paramedit(row, column, cell, event, index) {
        this.setShowEditInit()
        let nowObj = column.property
        var index = this.tableData.findIndex((item) => {
          return item.id === row.id
        })
        if (nowObj == 'compareOperator') {
          this.showCompareOperator[index] = true
          this.$set(this.showCompareOperator, index, true)
        } else if (nowObj == 'highestValue' && row.isHigh) {
          this.showHighestValue[index] = true
          this.$set(this.showHighestValue, index, true)
        } else if (nowObj == 'lowestValue' && row.isLow) {
          this.showLowestValue[index] = true
          this.$set(this.showLowestValue, index, true)
        } else if (nowObj == 'standardSource') {
          this.showStandardSource[index] = true
          this.$set(this.showStandardSource, index, true)
        } else if (nowObj == 'remindMethod') {
          this.showRemindMethod[index] = true
          this.$set(this.showRemindMethod, index, true)
        } else if (nowObj == 'logicOperator') {
          this.showLogicOperator[index] = true
          this.$set(this.showLogicOperator, index, true)
        }
      },
      handleSelectionChange(rows) {
        this.selectionRow = rows //保存已选择行
      },
      rowStyle({
        row,
        rowIndex
      }) {
        Object.defineProperty(row, 'rowIndex', { //给每一行添加不可枚举属性rowIndex来标识当前行
          value: rowIndex,
          writable: true,
          enumerable: false
        })
      },
      rowClassName({
        row,
        rowIndex
      }) {
        let rowName = "",
          findRow = this.selectionRow.find(c => c.rowIndex === row.rowIndex);
        if (findRow) {
          rowName = "current-row "; // elementUI 默认高亮行的class类 不用再样式了^-^,也可通过css覆盖改变背景颜色
        }
        return rowName; //也可以再加上其他类名 如果有需求的话
      },
      //点击表格每一行
      rowClick(row, event, column) {
        if (!row.add) {
          this.sqlText = row.sqlContext
        }
        let refsElTable = this.$refs.multiTable; // 获取表格对象
        // if (this.CtrlDown) {
        //   refsElTable.toggleRowSelection(row); // ctrl多选 如果点击两次同样会取消选中
        //   return;
        // }
        let findRow = this.selectionRow.find(c => c.rowIndex == row.rowIndex);
        if (this.CtrlDown && this.selectionRow.length > 0) {
          let topAndBottom = getTopAndBottom(row, this.bottomSelectionRow, this.topSelectionRow);
          refsElTable.clearSelection(); //先清空 不然会导致在这两行中间之外的行状态不变
          for (let index = topAndBottom.top; index <= topAndBottom.bottom; index++) { //选中两行之间的所有行
            refsElTable.toggleRowSelection(this.tableData[index], true);
          }
        } else {
          let findRow = this.selectionRow.find(c => c.rowIndex == row.rowIndex); //找出当前选中行
          //如果只有一行且点击的也是这一行则取消选择 否则清空再选中当前点击行
          if (findRow && this.selectionRow.length === 1) {
            refsElTable.toggleRowSelection(row, false);
            return;
          }
          refsElTable.clearSelection();
          refsElTable.toggleRowSelection(row);
        }
        // if (findRow) {
        //   refsElTable.toggleRowSelection(row, false);
        //   return;
        // }

        // refsElTable.clearSelection();
        // refsElTable.toggleRowSelection(row); // 调用选中行方法
      },
      keyDown(event) {
        let key = event.keyCode;
        if (key == 17) this.CtrlDown = true;
      },

      keyUp(event) {
        let key = event.keyCode;
        if (key == 17) this.CtrlDown = false;
        let right = document.getElementById('right')
        right.oncontextmenu = function(e) {
          //取消默认的浏览器自带右键 很重要！！
          e.preventDefault();

          //获取我们自定义的右键菜单
          var menu = document.querySelector("#menu");

          //根据事件对象中鼠标点击的位置，进行定位
          menu.style.left = e.clientX + 'px';
          menu.style.top = e.clientY + 'px';

          //改变自定义菜单的宽，让它显示出来
          menu.style.width = '70px';
          menu.style.height = '80px';
        }
        //关闭右键菜单，很简单
        right.onclick = function(e) {
          //用户触发click事件就可以关闭了，因为绑定在window上，按事件冒泡处理，不会影响菜单的功能
          document.querySelector('#menu').style.height = 0;
        }
      },
    },
    beforeDestroy() { //解绑
      removeEventListener("keydown", this.keyDown);
      removeEventListener("keyup", this.keyUp);
    }
  };
</script>

<style scoped lang="scss">
  .indicator-list {
    display: flex;
    padding: 10px;
    box-sizing: border-box;

    .left {
      width: 28%;
      // overflow-x: scroll;
    }

    .right {
      width:72%;
    }

    .edit {
      color: #1846BC
    }

    .right {
      margin: 50px 10px 0 10px;

      .sql-info {
        width: 100%;
        color: #000622;
        padding: 5px;
        box-sizing: border-box;
      }
    }

    #menu {
      width: 0;
      /*设置为0 隐藏自定义菜单*/
      height: 80px;
      overflow: hidden;
      /*隐藏溢出的元素*/
      box-shadow: 0 1px 1px #888, 1px 0 1px #ccc;
      position: absolute;
      background: white;
      /*自定义菜单相对与body元素进行定位*/
    }

    .menu {
      width: 70px;
      height: 25px;
      line-height: 25px;
      text-align: center;
      cursor: pointer;
    }

    .menu:hover {
      color: #0F49ED;
    }

    #canvas {
      position: absolute;
      top: 0;
      right: -30px;
    }
  }
</style>
